package feedback

import (
	"context"
	"strings"
	"time"

	"mall/common/modelx"
	"mall/common/utils/pointy"
	client "mall/service/recommended/common/gorseclient"
	"mall/service/recommended/rpc/internal/svc"
	"mall/service/recommended/rpc/types/recommended"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateBatchFeedbackLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateBatchFeedbackLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateBatchFeedbackLogic {
	return &CreateBatchFeedbackLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateBatchFeedbackLogic) CreateBatchFeedback(in *recommended.FeedbackList) (*recommended.BaseRowAffectedResp, error) {
	if len(in.List) == 0 {
		return &recommended.BaseRowAffectedResp{
			RowAffected: pointy.GetPointer(uint32(0)),
		}, nil
	}
	var feedbackList []client.Feedback
	now := modelx.FormatTime(time.Now(), "")
	for _, v := range in.List {
		if v.UserId != nil && len(strings.TrimSpace(*v.UserId)) > 0 &&
			v.ItemId != nil && len(strings.TrimSpace(*v.ItemId)) > 0 &&
			v.FeedbackType != nil || len(strings.TrimSpace(*v.FeedbackType)) > 0 {
			feedbackList = append(feedbackList, client.Feedback{
				UserId:       *v.UserId,
				ItemId:       *v.ItemId,
				FeedbackType: *v.FeedbackType,
				Timestamp:    now,
			})
		}
	}
	res, err := l.svcCtx.GorseClient.InsertFeedback(l.ctx, feedbackList)
	if err != nil {
		return nil, err
	}

	return &recommended.BaseRowAffectedResp{
		RowAffected: pointy.GetPointer(uint32(res.RowAffected)),
	}, nil
}
